package wibrst.keyboard {
	import flash.display.InteractiveObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;
	/**
	 * ...
	 * @author wibrst@qq.com
	 */
	public class SeqKeyDetector extends EventDispatcher {
		
		/// event const
		static public const SEQ_COMPLETE:String = "SEQ_COMPLETE";
		static public const ALL_COMPLETE:String = "ALL_COMPLETE";
		
		static public function getKeyCodeArrOfAlphabet( sAlphabet:String ):Array {
			var aKeyCode:Array = new Array;
			for ( var i:Number = 0; i < sAlphabet.length; ++ i ){
				aKeyCode.push( KeyConst.getKeyCodeOfChar( sAlphabet.charAt( i ) ) );
			}
			return aKeyCode;
		}
		
		/// --- --- --- start the class
		
		public function SeqKeyDetector( vInteract:InteractiveObject, id:String = "" ) {
			_id = id;
			setVInteract( vInteract );
		}
		
		public function setVInteract( vInteract:InteractiveObject ) {
			_vInteractHost = vInteract;
		}
		
		public function setKeyDetMission( aSeq:Array, nTotalTimesDet:Number = 1 ):void {
			if( _vInteractHost ){
				_vInteractHost.removeEventListener( KeyboardEvent.KEY_DOWN , keyHandler );
				if( aSeq.length ){
					_aSeqTgt = aSeq.concat();
					_nTimesDet = nTotalTimesDet;
					
					_vInteractHost.addEventListener( KeyboardEvent.KEY_DOWN , keyHandler );
					_pntSeq = -1;
				}
			}
		}
		
		public function releaseVInteract():void {
			if( _vInteractHost ){
				_vInteractHost.removeEventListener( KeyboardEvent.KEY_DOWN , keyHandler );
				_vInteractHost = null;
			}
		}
		
		private function keyHandler( evt:KeyboardEvent ):void {
			if ( evt.type == KeyboardEvent.KEY_DOWN ) {
				var pntSeqTo:Number = _pntSeq + 1;
				if ( evt.keyCode == _aSeqTgt[ pntSeqTo ] ) {
					_pntSeq = pntSeqTo;
					if ( _pntSeq == _aSeqTgt.length - 1 ) {
						dispatchEvent( new Event( SEQ_COMPLETE ) );
						if ( -- _nTimesDet < 1 ) {
							dispatchEvent( new Event( ALL_COMPLETE ) );
							_aSeqTgt = null;
							_aSeqTgt = new Array;
						}
						_pntSeq = -1;
					}
				}else {
					_pntSeq = -1;
				}
			}
		}
		
		/// control
		private var _nTimesDet:Number;
		private var _pntSeq:Number;
		
		private var _aSeqTgt:Array;
		
		/// dump
		private var _vInteractHost:InteractiveObject;
		private var _id:String;
		
		public function get id():String { return _id; }
		
	}

}